package com.erclab.xbuilder.managers;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;
import com.erclab.internal.xpresso.dataAccess.GenericResultSet;
import com.erclab.internal.xpresso.dataAccess.Query;
import com.erclab.internal.xpresso.exceptions.DataSourceException;
import com.erclab.xbuilder.exception.XBuilderException;

public class MysqlFormManager implements XBFormManager {

	protected ApplicationDataSource ads;
	
	public final String FORM_NAME_QUERY = "SELECT formName FROM app_forms WHERE IdForm=?";
	
	public MysqlFormManager(){
		int xbdatasource = Integer.parseInt(Settings.getProperty("xbuilder_app_meta.datasource"));		
		ads = Settings.getRepository().getApplicationDataSource(xbdatasource);
	}
	
	
	public int getNumberOfFields(String idForm) throws XBuilderException {
		Query q = new Query();
		q.setQuery("SELECT COUNT(*) as count FROM app_formelements WHERE IdForm=" + idForm);
		q.setValues(new String[]{});
		
		try {
			GenericResultSet grs = ads.runQuery(q);
			if (grs.nextRow()){
				return Integer.parseInt(grs.getValue("count"));
			} else {
				return 0;
			}
		} catch (DataSourceException e) {
			throw new XBuilderException("An error occurred counting number of rows", e);
		}
	}

	public String getFormName(String idForm) throws XBuilderException {
		Query q = new Query();
		q.setQuery(FORM_NAME_QUERY);
		q.setValues(new String[]{idForm});
		
		try {
			GenericResultSet grs = ads.runQuery(q);
			if (grs.nextRow()){
				return grs.getValue("formName");
			} else {
				return null;
			}
		} catch (DataSourceException e) {
			throw new XBuilderException("An error occurred counting number of rows", e);
		}
	}

}
